package com.spzx.auth.service;

import com.spzx.auth.form.H5RegisterBody;
import com.spzx.auth.form.LoginBody;
import com.spzx.common.core.constant.Constants;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.constant.UserConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.ip.IpUtils;
import com.spzx.common.core.utils.uuid.IdUtils;
import com.spzx.common.security.service.TokenService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.domain.SysUser;
import com.spzx.system.api.model.LoginUser;
import com.spzx.user.api.RemoteUserInfoService;
import com.spzx.user.api.domain.UserInfo;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class H5UserInfoService {
    @Resource
    RemoteUserInfoService remoteUserInfoService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    RedisTemplate redisTemplate;
    //登录：redis缓存登录状态
    @Resource
    TokenService tokenService;

    public int register(H5RegisterBody h5RegisterBody) {
        String username = h5RegisterBody.getUsername();
        String password = h5RegisterBody.getPassword();
        String nickName = h5RegisterBody.getNickName();
        String code = h5RegisterBody.getCode();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("手机号/密码必须填写");
        }
        if (username.length() != UserConstants.H5_USERNAME_LENGTH)
        {
            throw new ServiceException("账户长度必须为11位");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        //校验验证码是否正确：
        if (StringUtils.isEmpty(code) || code.length() != 4 ||
               !code.equals( stringRedisTemplate.opsForValue().get(Constants.APP_LOGIN_CODE_PRIFIX+username)))
        {
            throw new ServiceException("验证码错误");
        }
//        删除验证码
        stringRedisTemplate.delete(Constants.APP_LOGIN_CODE_PRIFIX+username);
        // 注册用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setPhone(username);
        userInfo.setNickName(nickName);
        R<Boolean> registerR = remoteUserInfoService.register(userInfo);

        if (R.FAIL == registerR.getCode())
        {
            throw new ServiceException(registerR.getMsg());
        }

        return 1;
    }

    public Map<String,Object> login(LoginBody loginBody) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("手机号/密码必须填写");
        }
        if (username.length() != UserConstants.H5_USERNAME_LENGTH)
        {
            throw new ServiceException("账户长度必须为11位");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        R<UserInfo> userInfoR = remoteUserInfoService.login(username, password);
        if (R.FAIL == userInfoR.getCode())
        {
            throw new ServiceException(userInfoR.getMsg());
        }

        //创建token
//        String token = IdUtils.fastSimpleUUID();
        // 保持登录状态：  使用token为键  userInfo为值存到redis中
        UserInfo userInfo = userInfoR.getData();
//        userInfo.setPassword(null);//数据脱敏 避免存到redis的数据包含密码

        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
//        loginUser.setToken(token);
        loginUser.setUsername(userInfo.getUsername());
        loginUser.setIpaddr(IpUtils.getIpAddr());
        loginUser.setLoginTime(System.currentTimeMillis());



//        redisTemplate.opsForValue().set(token ,userInfo , 7 , TimeUnit.DAYS);
        return tokenService.createToken(loginUser);
    }
    @CacheEvict(value = "spzx:user:info" , key = "#userId")
    public boolean logout(Long userId) {
        return true;
    }
}
